﻿using System;
using System.Collections.Generic;
using System.Dynamic;

namespace Lbb.Dynamic
{
    /// <summary>
    /// 动态字典.
    /// </summary>
    /// <author>Chiron</author>  
    public sealed class DynamicDictionary : DynamicObject
    {
        #region Fields
        private readonly Func<IDictionary<string, object>> _dataThunk;
        #endregion Fields

        #region Ctors
        public DynamicDictionary(Func<IDictionary<string, object>> dataThunk)
        {
            this._dataThunk = dataThunk;
        }
        public DynamicDictionary(IDictionary<string, object> data)
        {
            this._dataThunk = () => { return data; };
        }
        #endregion Ctors

        #region Methods
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return this.Dictionary.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this.Dictionary[binder.Name];
            return true;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this.Dictionary[binder.Name] = value;
            return true;
        }
        #endregion Methods

        #region Props
        public IDictionary<string, object> Dictionary
        {
            get
            {
                return this._dataThunk();
            }
        }
        #endregion Props
    }
}
